package com.zhenai.rocyuan.commons.uitls.cookie;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.zhenai.rocyuan.commons.uitls.DesCrypto;

public class SessionInCookie implements Map<String, String> {

	private Map<String, String> session;

	private static final String PASSWORD = "fkpdghi8w";

	public SessionInCookie() {
		session = new HashMap<String, String>();
	}

	public SessionInCookie(String cookie) {
		this();
		if (StringUtils.isEmpty(cookie)) {
			return;
		}
		cookie = DesCrypto.decrypt(cookie, PASSWORD);
		if (StringUtils.isEmpty(cookie)) {
			return;
		}
		String[] lines = StringUtils.split(cookie, '\n');
		for (String line : lines) {
			String key = StringUtils.substringBefore(line, "=");
			String value = StringUtils.substringAfter(line, "=");
			session.put(key, value);
		}
	}

	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (String key : session.keySet()) {
			sb.append(key).append("=");
			String value = session.get(key);
			if (value != null) {
				sb.append(value);
			}
			sb.append('\n');
		}
		return DesCrypto.encrypt(sb.toString(), PASSWORD);
	}

	@Override
	public void clear() {
		session.clear();
	}

	@Override
	public boolean containsKey(Object key) {
		return session.containsKey(key);
	}

	@Override
	public boolean containsValue(Object value) {
		return session.containsValue(value);
	}

	@Override
	public Set<java.util.Map.Entry<String, String>> entrySet() {
		return session.entrySet();
	}

	@Override
	public String get(Object key) {
		return session.get(key);
	}

	@Override
	public boolean isEmpty() {
		return session.isEmpty();
	}

	@Override
	public Set<String> keySet() {
		return session.keySet();
	}

	@Override
	public String put(String key, String value) {
		return session.put(key, value);
	}

	public String put(String key, Object value) {
		if (value != null) {
			return put(key, value.toString());
		} else {
			return session.put(key, "");
		}
	}

	@Override
	public void putAll(Map<? extends String, ? extends String> m) {
		session.putAll(m);
	}

	@Override
	public String remove(Object key) {
		return session.remove(key);
	}

	@Override
	public int size() {
		return session.size();
	}

	@Override
	public Collection<String> values() {
		return session.values();
	}

	public static void main(String[] args) {
		SessionInCookie session = new SessionInCookie();
		session.put("111", "11111");
		session.put("222", "22222");
		System.out.println(session.toString());
		session = new SessionInCookie("fb6c8148eb5e0b9d27cbbe0d5381060a1ea3276f8d73f73a");
		for (String key : session.keySet()) {
			System.out.print(key);
			System.out.print("=");
			System.out.println(session.get(key));
		}
	}
}
